package com.stress.testing.plugin.apache.http.client.v3.interceptor;

import com.stress.testing.common.StressTesting;
import com.stress.testing.common.TraceContext;
import com.stress.testing.common.TraceContextHolder;
import com.stress.testing.common.interceptor.AbstractInterceptor;
import org.apache.commons.httpclient.HttpMethod;

import java.lang.reflect.Method;


public class HttpClientExecuteMethodInterceptor extends AbstractInterceptor {
    @Override
    public void before(Method method, Object[] args, Object zuper, Object thiz) {
        if (!StressTesting.enable(getAgentConfig(), getPluginConfig())) {
            return;
        }

        if (args == null || args.length != 3) {
            return;
        }

        Object arg = args[1];

        if (!(arg instanceof HttpMethod)) {
            return;
        }

        HttpMethod httpMethod = (HttpMethod) arg;

        TraceContext traceContext = TraceContextHolder.getTraceContext();
        if (traceContext == null) {
            return;
        }

        // 添加链路信息
        for (String name : traceContext.propertyNames()) {
            httpMethod.addRequestHeader(name, traceContext.getProperty(name));
        }
    }
}
